<template>
  <div style="display: flex; height: 100%; flex: 1;">
    <HierarchyList :pagination="pagination" :columns="columns" :load-data="loadData"
                   :export-label="exportLabel" :export-asset="exportClients"
                   :import-label="importLabel" :import-asset="importClients"
                   ref="refHiRole" :search-form="searchItems" :create-label="addClientLabel"
                   :add-item="addClient" />
    <EditDialog ref="refEditDlg" :columns="columns" :rules="rules" :submit="onSubmit"
                :form-label-width="100" :is-show-dialog="false"/>

    <ImportDataDialog ref="refImport" url="/uni-center/v1/excel/asset/import/type"
                      :tips="'是否更新已经存在的客户端数据'" :do-upload="uploadAction" />
  </div>
</template>

<script setup lang="ts">

import {computed, onMounted, ref, toRaw} from "vue";
import HierarchyList from "@/views/sop/list/HierarchyList.vue";
import {buildSearchForms} from "@/views/sop/data/PageData";
import {msgError, msgInfo} from "@/utils/InfoUtil";
import EditDialog from "@/components/common/EditDialog.vue";
import {create32} from "@/utils/StrUtil";
import {buildAsset} from "@/utils/sop/DataUtil";
import {currentNames, TYPES} from "@/stores/conf";
import {useCurrent} from "@/utils/sop/UseCurrentFunc";
import {useAssetOp} from "@/utils/sop/UseAssetOp";
import {useTerminal} from "@/utils/sop/UseTerminal";
import {exportAssetByType, getStateOptions, getStateTag, getStateText, handleResult} from "@/utils/SystemUtil";
import {requestForm} from "@/apis/request";
import {useStore} from "@/stores";
import ImportDataDialog from "@/widget/ImportDataDialog.vue";
import {hasMenuPermit} from "@/utils/sop/PermitUtil";

const props = withDefaults(defineProps<{
  product?: boolean,
  entry: any,
}>(), {});

const store = useStore();
const refImport = ref();
const refHiRole = ref();
const refEditDlg = ref();

const currentItem = ref();

const {updateCurrent} = useCurrent(currentNames.CLIENT);
const {doLoadAsset, doSaveAsset, doDeleteAsset} = useAssetOp(props.entry);

const {onTerminal} = useTerminal(currentNames.CLIENT);

const searchItems = ref(buildSearchForms('客户端', {
  show: props.product,
  onChanged: onTerminal,
}));

const rules = ref({
  name: [{required: true, message: '请输入客户端名称', trigger: ['blur']}],
  code: [{required: true, message: '请输入客户端标识', trigger: ['blur']}],
})

const addClientLabel = computed(() => {
  return hasMenuPermit('asset:client:add') ? '新增客户端' : '';
})

const importLabel = computed(() => {
  return hasMenuPermit('asset:client:import') ? '导入' : '';
})

const exportLabel = computed(() => {
  return hasMenuPermit('asset:client:export') ? '导出' : '';
})

const getTargetId = () => {
  return '';
}

const importClients = () => {
  refImport.value.handleImport();
}

const exportClients = async (parentId: string='') => {
  const platform: any = store.getCurrentPlatform();

  await exportAssetByType({
    platformId: platform.id,
    assetType: TYPES.CLIENT
  }, `${TYPES.CLIENT}_${new Date().getTime()}.xlsx`, {});
}

const uploadAction = async (option: any, url: any, headers: any) => {
  const platform: any = store.getCurrentPlatform();
  let formData: any = new FormData();
  formData.append("file", option.file);
  formData.append("assetType", TYPES.CLIENT);
  formData.append("platformId", platform.id);

  await requestForm({
    url: url,
    method: 'post',
    headers: headers,
    data: formData,
  });
  refresh();
}

const loadData = async (params: any) => {
  const result = await doLoadAsset(getTargetId(), TYPES.CLIENT, params);

  if (result && result.code === 0) {
    msgInfo('加载客户端信息成功!');
    handleResult(result.data, ['secret', 'comment','accessTimeout','refreshTimeout']);
  } else {
    msgError(result ? result.message : '加载客户端信息失败！');
  }

  return result;
}

const refresh = (params: any = {}) => {
  refHiRole.value?.refresh({
    ...params,
  })
}

const onSubmit = async (item: Record<string, any>) => {
  let assetInfo = buildAsset(item, TYPES.CLIENT, {
    secret: item.secret,
    accessTimeout: item.accessTimeout,
    refreshTimeout: item.refreshTimeout,
  });

  const result = await doSaveAsset(getTargetId(), assetInfo);

  if (result && result.code === 0) {
    msgInfo('保存客户端信息成功!');
    setTimeout(() => refresh(),300);
  } else {
    msgError(result ? result.message : '保存客户端信息失败！');
  }

  return result;
}

const newClient = () => {
  return {
    state: 1,
    secret: create32(),
    type: TYPES.CLIENT,
    accessTimeout: 300,
    refreshTimeout: 300,
  };
}

const pagination = ref({
  current: 1,
  pageSize: 20,
  total: 0,
});

const columns = ref([
  {
    id: 'id',
    name: '标识',
    hideCol: true,
    show: false,
    canEdit: false,
  },
  {
    id: 'name',
    name: '客户端名称',
    sort: 'custom',
    show: true,
    action: (data: any, row: any, index: number) => {
      updateCurrent({type: TYPES.CLIENT, ...row})
    }
  },
  {
    id: 'code',
    name: '客户端标识',
    show: true,
    canEdit: true,
  },
  {
    id: 'secret',
    name: '客户端秘钥',
    show: true,
    readOnly: true,
    extBtn: {
      name: '重新生成',
      action: (item: any) => {item.secret = create32();}
    }
  },
  {
    id: 'accessTimeout',
    name: '访问超时(秒)',
    show: true,
  },
  {
    id: 'refreshTimeout',
    name: '刷新超时(秒)',
    show: true,
  },
  {
    id: 'createTime',
    name: '创建时间',
    show: true,
    canEdit: false,
  },
  {
    id: 'state',
    name: '状态',
    show: true,
    tag: 'true',
    type: 'select',
    tagType: (tag: number) => { return getStateTag(tag); },
    tagText: (tag: number) => { return getStateText(tag); },
    options: getStateOptions()
  },
  {
    id: 'operation',
    name: '操作',
    show: true,
    hideCol: true,
    canEdit: false,
    fixed: 'right',
    operations: [
      {
        name: '编辑',
        disabled: (row: any) => {
          return !hasMenuPermit('asset:client:edit');
        },
        callback: (data: any, row: any) => {
          currentItem.value = toRaw(row)
          refEditDlg.value?.editUpdate('编辑客户端', toRaw(row))
        }
      },
      {
        name: '删除',
        type: 'confirm',
        disabled: (row: any) => {
          return !hasMenuPermit('asset:client:delete');
        },
        confirm: async (data: any, row: any) => {
          const result = await doDeleteAsset(getTargetId(), row);
          if (result.code === 0) {
            msgInfo('删除客户端信息成功！');
            setTimeout(() => refresh(), 300);
          } else {
            msgError(result.message ? result.message : '删除客户端信息失败！');
          }
        },
        cancel: () => {
        }
      }
    ]
  }
]);

const addClient = () => {
  currentItem.value = newClient();
  refEditDlg.value?.editAdd('新增客户端', currentItem.value);
}

onMounted(() => {

})

defineExpose({
  refresh,
})

</script>

<style scoped>
.el-form-item-class .el-form-item__label {
  font-size: 12px;
}

</style>
